#include "deal_network_status.h"

#include<QTcpSocket>
#include<QDebug>

DealNetworkStatus::DealNetworkStatus()
{
    //启动定时器：用于发送心跳
    m_timer = new QTimer(this);
    m_timer->setTimerType(Qt::PreciseTimer);
    //连接定时器的信号与槽，定时时间一到就会发送 timeout() 信号，从而触发槽函数dealHeartBeat（处理心跳）
    connect(m_timer, &QTimer::timeout,
            this, &DealNetworkStatus::testNetworkStatus);//心跳处理
    //每隔 “time” 秒重启心跳定时器
    qDebug()<<"monitorNetworkStatus";
}

void DealNetworkStatus::stopMonitorNetwork()
{
    m_timer->stop();
}

void DealNetworkStatus::startMonitorNetwork()
{
    qDebug()<<"m_timer->start(1000)";
    m_timer->start(1000);//1000ms
}

#include <QLibrary>

typedef bool(*ConnectFun)(int* lpdwFlags, int  dwReserved);

bool DealNetworkStatus::testNetworkStatus()
{
    QLibrary lib("Wininet.dll");
    if (lib.load())
    {
        bool bOnline = false;//是否在线
        int  flags;

        //获取dll库中的函数InternetGetConnectedState函数地址`
        ConnectFun  myConnectFun = (ConnectFun)lib.resolve("InternetGetConnectedState");

        //判断是否连网
        bOnline = myConnectFun(&flags, 0);
        if(bOnline){
            // qDebug() << __FUNCTION__ << "isOnline = true";
            emit sendNetworkStatus(NetworkStatus::Normal);
            return true;
        }
        else{
            //qDebug() << __FUNCTION__ << "isOnline = false";
            emit sendNetworkStatus(NetworkStatus::Disconnect);
            return false;
        }

    }
    return false;
}
